<template>
  <div class="content-box">
    <div ref="searchBox" class="search-box flex" v-show="showSearch">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="100px"
      >
      <el-form-item label="公司集合" prop="companyIds">
        <el-select
          v-model="queryParams.companyIds"
          multiple
          collapse-tags
          clearable
          filterable
          placeholder="请选择"
          style="width: 240px; margin-right: 20px"
          @change="companyIdsChange"
        >
          <el-option
            v-for="(item, index) in companyIdOptionList"
            :key="index"
            :label="item.companyName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品集合" prop="productIds">
        <el-select
          v-model="queryParams.productIds"
          multiple
          collapse-tags
          clearable
          filterable
          placeholder="请选择"
          style="width: 240px; margin-right: 20px"
        >
          <el-option
            v-for="(item, index) in productIdOptionList"
            :key="index"
            :label="item.productName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            plain
            >查询</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div class="table-box">
      <el-row :gutter="10" class="mb8">
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="handleQuery"
          :columns="columnsList"
        ></right-toolbar>
      </el-row>
      <el-table
        v-sticky-header
        ref="table"
        v-loading="loading"
        :data="dataList"
        :span-method="objectSpanMethod"
        border
      >
        <template v-for="(item,index) in columns.slice(0,columns.length - 1)">
          <el-table-column
            :key="index"
            :label="item.label"
            :prop="item.prop"
            :width="getColumnWidth(index)"
            :fixed="item.fixed"
            :sortable="item.sortable ? item.sortable : false"
            :show-overflow-tooltip="item.showTooltip"
            v-if="item.visible"
            align="center"
          >
             <template slot-scope="scope">
                <!-- 分配模式单独处理 -->
                <div v-if="item.prop == 'shareType'">
                    <el-popconfirm
                      :title="`确定重新${
                        !scope.row[item.prop] ? '抢单' : '派单'
                      }吗？`"
                      @confirm="changeShareType(scope.row)"
                    >
                      <el-button
                        slot="reference"
                        size="mini"
                        :style="{
                          color:'#fff',
                          backgroundColor: scope.row[item.prop]?'#fa8c16':'#5AA4AE',
                          borderColor: scope.row[item.prop]?'#fa8c16':'#5AA4AE',
                        }"
                        >{{ scope.row[item.prop] ? "抢单" : "派单" }}</el-button
                      >
                    </el-popconfirm>
                </div>
                <!-- 余额单独处理 -->
                <div v-else-if="item.prop == 'isSurplus'">
                    <el-popconfirm
                      :title="`确定重新${
                        !scope.row[item.prop] ? '显示' : '不显示'
                      }吗？`"
                      @confirm="changeIsSurplus(scope.row)"
                    >
                      <el-button
                        slot="reference"
                        size="mini"
                        :style="{
                          color:'#fff',
                          backgroundColor: scope.row[item.prop]?'#7cb305':'#096dd9',
                          borderColor: scope.row[item.prop]?'#7cb305':'#096dd9',
                        }"
                        >{{ scope.row[item.prop] ? "显示" : "不显示" }}</el-button
                      >
                    </el-popconfirm>
                </div>
                <!-- 产品状态单独处理 -->
                <div v-else-if="item.prop == 'child_productStatus'">
                    <el-tag 
                     :type="productStatusColor(scope.row[item.prop])" 
                     >
                     {{ ArrayFormatObj(productStatusOptions)[scope.row[item.prop]]}}
                    </el-tag>
                </div>
                <span v-else>
                  {{  scope.row[item.prop]  }}
                </span>
             </template>
          </el-table-column>
        </template>
        <el-table-column
          fixed="right"
          :prop="columns[columns.length - 1].prop"
          :label="columns[columns.length - 1].label"
          align="center"
          :width="getColumnWidth(columns.length - 1,'columns')"
          v-if="columns[columns.length - 1].visible"
        >
          <template slot-scope="scope">
            <div :class="['flex-center',device === 'mobile'?'flex':'']">
                <el-button
                 type="text"
                 style="color: #ad6800"
                 @click="handelProductPlan('产品计划', scope.row)"
                 v-hasPermi="['business:product:prodectPlan']"
                 >产品计划</el-button
               >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 使用分页插件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page-sizes="[10, 50, 100, 200, 500]"
        :page.sync="queryParams.pageIndex"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
     <!-- 产品计划组件 -->
    <TimeSlot ref="productPlanRef"></TimeSlot>
  </div>
</template>

<script>
import tableStickyMixins from "@/mixins/tableStickyMixins";
import { mapGetters } from "vuex";
import TimeSlot from '@/components/TimeSlot'
import {
  queryCrmCompanyByPage,
  setShareType,
  queryCrmCompanyList,
  queryCrmProductList,
  setIsSurplus,
} from "@/api/sysCrm/crmCompany";
export default {
  // 定义名字用于标识该组件是否被keep-alive缓存
  name: "CrmCompany",
   components:{
    TimeSlot,
  },
  data() {
    return {
      // 数据列表
      dataList: [],
      // 公司集合筛选项
      companyIdOptionList: [],
      // 产品筛选列表
      productIdOptionList: [],
      // 产品状态筛选项
      productStatusOptions: [
        { label: "在线", value: '0' },
        { label: "下线", value: '1' },
        { label: "停用", value: '2' },
      ],
      // 分配模式筛选项
      shareTypeOptions: [
        { label: "派单", value: 0 },
        { label: "抢单", value: 1 },
      ],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
      },
      loading: false,
      // 表格列信息（用于控制显示与隐藏)
      columnsList:[],
      // 显示搜索栏
      showSearch: true,
    };
  },
  mixins: [tableStickyMixins],
  watch: {
    columns: {
      handler() {
        this.updateTableHeight();
      },
      deep: true,
    },
  },
  created() {
    this.getProductIdList()
    this.getCompanyIdList()
    this.getList();
  },
  computed: {
    ...mapGetters(["sidebar", "device"]),
    // 计算当前列元素在所处环境的宽度
    getColumnWidth() {
      return (index) => {
        return this.isMobile
          ? this.columns[index].mobileWidth
          : this?.sidebar?.opened
          ? this.columns[index].pcWidth - this.slightWidth
          : this.columns[index].pcWidth + 17;
      };
    },
    // 将数组转换为对象形式
    ArrayFormatObj:()=>{
       return (arr)=>{
         return arr.reduce((pre, cur)=>{
           pre[cur.value] = cur.label;
           return pre;
         },{})
       }
    },
     // 产品状态标签颜色处理
    productStatusColor:()=>{
        return (state)=>{
           switch(state){
             case '0':
                return 'success';
             case '1':
                return '';
             case '2':
                return 'danger';
             default:
           }
        }
    },
    // 表格列信息
    columns(){
      const arr = [
       {label: `公司简称`,prop: "companyName",visible: true,pcWidth: 'auto',mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `分配模式`,prop: "shareType",visible: true,pcWidth: 200,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `余额`,prop: "isSurplus",visible: true,pcWidth: 200,mobileWidth: 120,fixed: null,showTooltip: true,},

       {label: `产品名称`,prop: "child_productName",visible: true,pcWidth: 'auto',mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `产品状态`,prop: "child_productStatus",visible: true,pcWidth: 200,mobileWidth: 120,fixed: null,showTooltip: true,},
       {label: `跟进人数量`,prop: "child_userNum",visible: true,pcWidth: 200,mobileWidth: 150,fixed: null,showTooltip: true,},
       {label: `操作`,prop: "operation",visible: true,pcWidth: 100,mobileWidth: 100,fixed: "right",showTooltip: true},
      ]
      this.$set(this,'columnsList',arr)
      return arr
    }
  },
  methods: {
    // 公司集合改变重新查询获取产品筛选列表
    companyIdsChange(value){
      this.getProductIdList()
    },
    // 获取公司筛选项列表
    getCompanyIdList(){
      queryCrmCompanyList().then(res=>{
        this.companyIdOptionList = res.data
      })
    },
    // 获取产品筛选列表
    getProductIdList(){
      queryCrmProductList({
        companyIds:this?.queryParams?.companyIds
      }).then(res=>{
        this.productIdOptionList = res.data
      })
    },
    // 分配模式切换触发回调
    changeShareType(row) {
      const params = {
        id: row?.id,
        shareType: row?.shareType ? 0 : 1,
      };
      setShareType(params).then((res) => {
        if (res.code === 200) {
          this.$message.success("操作成功");
          this.getList();
        }
      });
    },
    // 余额切换触发回调
    changeIsSurplus(row) {
      const params = {
        id: row?.id,
        isSurplus: row?.isSurplus ? 0 : 1,
      };
      setIsSurplus(params).then((res) => {
        if (res.code === 200) {
          this.$message.success("操作成功");
          this.getList();
        }
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.$set(this.queryParams, "pageIndex", 1);
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 完全重置到初始状态
      this.$set(this, "queryParams", {
        pageIndex: 1,
        pageSize: 10,
      });
      this.getList();
    },
    // 表格合并处理
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
       // 过滤隐藏项合并父级列,排除操作项
       if (!this.columns.filter(pre=>pre?.visible)[columnIndex].prop.includes('child_') && !this.columns.filter(pre=>pre?.visible)[columnIndex].prop.includes('operation')) {
           if (row?.childNum) {
             return {
               rowspan: row?.childNum,
               colspan: 1
             };
           } else {
             return {
               rowspan: 0,
               colspan: 0
             };
           }
       } 
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      queryCrmCompanyByPage(this.queryParams).then((response) => {
        // 处理合并数据
        this.dataList = response?.data?.list?.reduce((arr,pre)=>{
          if(pre?.productList?.length){
            // 子项数量
            let childNum = pre?.productList?.length
            arr.push(...pre.productList.map((item,index)=>{
              // 如果为初始项设置子项数量
              if(index === 0){
                  return  {
                    ...pre,
                    ...this.prefixKeys(item,'child_'),
                    childNum
                  }
              }
              return {
                ...pre,
                ...this.prefixKeys(item,'child_')
              }
            }
          ))
          }else{
            arr.push(pre)
          }
          return arr
        },[])
        this.total = response?.data?.total;
        this.loading = false;
      }).catch((err) => {
        setTimeout(() => {// 延迟2s后自动取消
          this.loading = false;
        }, 2000);
      })
    },
    // 重置属性转化为新对象
    prefixKeys(obj, prefix) {
         return Object.keys(obj).reduce((acc, key) => {
           acc[prefix + key] = obj[key];
           return acc;
         }, {});
    },
    // 修改表格高度触发回调
    updateTableHeight() {
      this.$nextTick(() => {
        this.$refs.table.doLayout();
      });
    },
    // 打开产品计划对胡框
    handelProductPlan(title,row = null){
      let data = JSON.parse(JSON.stringify(row))
      // 这里单独处理一下产品id
      data.id = data?.child_productId
      this.$refs.productPlanRef.openHandle(data)
    }
  },
};
</script>

<style scoped lang="scss">
.title {
  font-size: 20px;
  color: #333333;
  font-weight: 500;
}
.search-box {
  margin: 0 0 20px;
  padding: 20px 20px 0;
  background: #fff;
  align-items: flex-start;
  border-radius: 6px;
}
.search-area {
  position: absolute;
  right: 20px;
}
.el-form-item__content {
  flex: 1;
  line-height: 40px;
  position: relative;
  font-size: 14px;
  min-width: 0;
}
::v-deep .el-dialog__body {
  border-top: 1px solid #dfe6ec;
  border-bottom: 1px solid #dfe6ec;
}
.el-table {
  // 滚动条加粗
  --scrollbar-height: 9px;
}
</style>
